public without sharing class ContractLinkPriceController {

	public String msg {get;set;}

	public Boolean isSuccess {get;set;}

	public Boolean isErr {get;private set;}

	public String backId {get;set;}

	public String conId {get;set;}//合同ID;

	public String paramJson {get;set;}//传递的参数json 

	public String searchJson {get;set;}///搜索

	public String resJson {get;set; }//结果

	public Boolean isParent ;

	public Contract__c con ;

	public User u ;

	///筛选条件
	public String 	pname {get;set;}
    public String	pbrand {get;set;}
    public String	pspec {get;set;}
    public String	pnccode {get;set;}
    public String	pserialNo {get;set;}
    public String	pcategory0 {get;set;}
    public String	pcategory1 {get;set;}
    public String	productType {get;set;}
    public String 	quotenu {get;set;}
    public String 	measurenu {get;set;}
    public String  	adpricenu {get;set;}
	///

    public ContractLinkPriceController() {
		resJson = '[]';
        conId = System.currentPageReference().getParameters().get('id');
        con = new Contract__c();
        u = [select Id,subCompany__c from User where Id =:UserInfo.getUserId()];
    }


    public void init(){

    	if(conId == null){
    		setErr('页面打开错误!');
    		return;
    	}
    	 con = [select Id ,Account__c ,Account__r.ParentId ,Status__c,Vsalestrucode__c from Contract__c where Id=:conId];
    	if(con == null){
    		setErr('页面打开错误!');
    		return;
    	}
        if(con.Status__c ==  '审批中' ){
            setErr('合同审批中不能关联价目表!');
            return;
        }

    	if(con.Status__c == '已生效' ){
    		setErr('合同已生效不能关联价目表!');
    		return;
    	}
    	//判断是否为第三方体系
    	//isParent = con.Account__r.ParentId == null ? false : true;


    }


    ///设置错误信息
 	public void setErr(String errMsg ){
    	isErr = true;
        ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,errMsg));
    }

    //获取合同产品
    public void getContractProducts(){

    	Set<String> cset = new Set<String>();
    	cset.add('仪器');
    	cset.add('辅助器械');


           List<ContractProductBean> tmp = new List<ContractProductBean>();
           List<Object> trL = new List<Object> ();
         for(ContractProduct__c cp :[select Id ,Product__c,Product__r.Name ,Product__r.Category0__c,
          Product__r.Category1__c,Product__r.Category2__c,Product__r.Brand__c,Product__r.Spec__c,Product__r.SerialNo__c,
          Product__r.TypeName__c,Product__r.Model__c,Product__r.NCCode__c ,SalesPrice__c 

         from ContractProduct__c where Contract__c =:con.Id and Product__r.Category0__c   not in:cset ]){
         		ContractProductBean cpb = new ContractProductBean(cp);
         		tmp.add(cpb);
         		//trL.add(cpb.genTableJson());
         	
         }
         	//setTableData(tmp);
         // System.debug('===>'+ImportObject.saveExelBlob('['+JSON.serialize(trL)+']'));

 	    	paramJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');




    }
      
    ///获取价目表
    public void getPriceListProducts(){

    	String sql = 'select Product__c,Product__r.Brand__c,Product__r.Spec__c,Product__r.SerialNo__c,Product__r.Model__c ,';
    		sql += 'Product__r.Category1__c,Product__r.Category2__c,Product__r.Category0__c,Product__r.zl__c,Product__r.NCCode__c,';
    		sql += 'Product__r.Name,SalesCode__c,Price__c,Id,Product__r.SealCompany__c ,Product__r.TypeName__c,  ';

    		sql += 'Quote__r.Name ,Measure_Calculate__r.Name,JustPriceProduct__r.AdjustPrice__r.Name from PriceList__c ';

    		sql += ' where Account__c =\''+con.Account__c+'\' ';

    		sql +=' and  SalesCode__c=\''+con.Vsalestrucode__c+'\'' ;

    		System.debug('***'+sql);
    	
    	 
    	 if(String.isBlank(pname) == false ) sql += ' and Product__r.Name like \'%'+pname+'%\' ';
    	 if(String.isBlank(pbrand) == false ) sql += '  and Product__r.Brand__c like \'%'+pbrand+'%\' ';
    	 if(String.isBlank(pspec) == false ) sql += '  and Product__r.Spec__c like \'%'+pspec+'%\' ';
    	 if(String.isBlank(pnccode) == false ) sql += '  and Product__r.NCCode__c like \'%'+pnccode+'%\' ';
    	 if(String.isBlank(pcategory0) == false ) sql += '  and Product__r.Category0__c like \'%'+pcategory0+'%\' ';
    	 if(String.isBlank(pcategory1) == false ) sql += '  and Product__r.Category1__c like \'%'+pcategory1+'%\' ';
    	 if(String.isBlank(pserialNo) == false ) sql += '  and Product__r.SerialNo__c like \'%'+pserialNo+'%\' ';


    	 if(String.isBlank(quotenu) == false ) sql += '  and  Quote__r.Name like \'%'+quotenu+'%\' ';
    	 if(String.isBlank(measurenu) == false ) sql += '  and  Measure_Calculate__r.Name like \'%'+measurenu+'%\' ';
    	 if(String.isBlank(adpricenu) == false ) sql += '  and  JustPriceProduct__r.AdjustPrice__r.Name like \'%'+adpricenu+'%\' ';

           List<ContractProductBean> tmp = new List<ContractProductBean>();


    	for(PriceList__c p : Database.query(sql)){

         	tmp.add(new ContractProductBean(p));

    	}
 	    paramJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');


    }
    public void save(){

    		msg = '';
    	System.debug('**'+resJson);
    	List<Object> resList=(List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(resJson, 'UTF-8'));
    		
    	if(resList.size() == 0){
    		msg = '保存失败,没有数据!';
    		return;
    	}
		List<ContractProduct__c> cpList = new List<ContractProduct__c>();
    	for (Object res : resList) {
    		Map<String ,Object> o = (Map<String ,Object> )res;
    		ContractProduct__c cp = new ContractProduct__c();
    		cp.Contract__c = con.Id;
    		String productId = o.get('productId') == null ? null : String.valueOf(o.get('productId'));
    		if(productId == null ){
    			msg = o.get('productName') +'的产品ID为空,不能保存!';
    			break;
    		}else{
    			cp.Product__c = productId;
    		}

    		if(o.get('price') != null){
    			cp.SalesPrice__c = Decimal.valueOf(String.valueOf(o.get('price')));
    		}

    		if(o.get('cate0') != null ){
    			cp.Classification__c = String.valueOf(o.get('cate0'));
    		}

    		cpList.add(cp);

    	}

    	if(msg.length() > 0)return;
    	SavePoint sp = Database.setSavepoint();
    	try{
    		Set<String> cset = new Set<String>();
    		cset.add('仪器');
    		cset.add('辅助器械');
    		List<ContractProduct__c> deleList = [select Id from ContractProduct__c where Contract__c =: con.Id and Product__r.Category0__c   not in:cset];
	    	if(deleList != null && deleList.size() > 0) delete deleList;
	    	insert cpList;
            msg = '保存成功!';

    	    isSuccess = true;
    	    backId = con.Id;
        }catch (Exception e){
        	 Database.rollback(sp);
    	    isSuccess = false;
    	    System.debug('***'+e);
    	    msg = '保存失败!' +e.getMessage();
        }   


    }
    public void search(){
    	pname = '';
    	pbrand = '';
    	pspec = '';
    	pnccode = '';
    	pserialNo = '';
    	pcategory0 = '';
    	pcategory1 = '';
    	productType = '';

    	System.debug('***'+searchJson); 
    	//System.debug('***'+EncodingUtil.urlDecode(searchJson, 'UTF-8')); 
    	Map<String,Object> searchMap =(Map<String,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));
    	String type = getKeyValue(searchMap,'type');
    	String productName = getKeyValue(searchMap,'productName'); 
		String brand = getKeyValue(searchMap,'brand');
		String spec = getKeyValue(searchMap,'spec'); 
		String cate0 = getKeyValue(searchMap,'cate0'); 
		String nccode = getKeyValue(searchMap,'nccode'); 
		String cate1= getKeyValue(searchMap,'cate1'); 
		String serialNo= getKeyValue(searchMap,'serialNo'); 
		String ptype= getKeyValue(searchMap,'ptype'); 

		String qn = getKeyValue(searchMap,'quotenum');
		String mn  =getKeyValue(searchMap,'measurenum'); 
		String an =getKeyValue(searchMap,'adpricenum');


		if( productName != null && productName != '')pname = productName;
		if( brand != null && brand != '')pbrand = brand;
		if( spec != null && spec != '')pspec = spec;
		if( cate0 != null && cate0 != '')pcategory0 = cate0;
		if( cate1 != null && cate1 != '')pcategory1 = cate1;
		if( nccode != null && nccode != '')pnccode = nccode;
		if( serialNo != null && serialNo != '')pserialNo = serialNo;
		if( ptype != null && ptype != '')productType = ptype;
		if( qn != null && qn != '')quotenu = qn;

		if( mn != null && mn != '')measurenu = mn;
		if( an != null && an != '')adpricenu = an;

		getPriceListProducts();


    	
    }

    public String getKeyValue(Map<String,Object> m ,String key){

    	String s = String.valueOf(m.get(key)) ;
    	if(s == null) return null;
    	return s.trim();
    }
    ///置空参数
    public void setNil(){
    	paramJson = '';
    	searchJson = '';
    	resJson = '[]';

    	pname = '';
    	pbrand = '';
    	pspec = '';
    	pnccode = '';
    	pcategory0 = '';
    	pcategory1 = '';
    	quotenu = '';
    	measurenu = '';
    	adpricenu = '';
    
    }


    public class ContractProductBean{

     	public String productId {get;set;}//产品ID
    	public String productName {get;set;}//产品名称
    	public String brand {get;set;}//品牌
    	public String  spec {get;set;}//规格
    	public String  serialNo {get;set;}//货号
    	public String  model {get;set;}//型号
    	public String  nccode {get;set;}//存货编码
    	public String  productType {get;set;}//产品类型

    	public String cate0 {get;set;}//主分类
    	public String cate1 {get;set;}//一级分类
    	public String cate2 {get;set;}//二级分类

    	public Decimal price {get;set;}

    	public String qNum {get;set;}//报价编号
    	public String mNum {get;set;}//测算编号
    	public String adNum {get;set;}//新增/条件编号

    	public String priceListId {get;set;}//产品价目ID

    	public ContractProductBean(ContractProduct__c cp){

    		productId = cp.Product__c;
    		productName = cp.Product__r.Name;
    		brand = cp.Product__r.Brand__c;
    		spec = cp.Product__r.Spec__c;
    		serialNo = cp.Product__r.SerialNo__c;
    		model = cp.Product__r.Model__c;
    		nccode = cp.Product__r.NCCode__c;
    		productType = cp.Product__r.TypeName__c;

    		cate0 = cp.Product__r.Category0__c;
    		cate1 = cp.Product__r.Category1__c;
    		cate2 = cp.Product__r.Category2__c;
    		price = cp.SalesPrice__c;


    	}
    	public ContractProductBean(PriceList__c cp){
    		productId = cp.Product__c;
    		productName = cp.Product__r.Name;
    		brand = cp.Product__r.Brand__c;
    		spec = cp.Product__r.Spec__c;
    		serialNo = cp.Product__r.SerialNo__c;
    		model = cp.Product__r.Model__c;
    		nccode = cp.Product__r.NCCode__c;
    		productType = cp.Product__r.TypeName__c;

    		cate0 = cp.Product__r.Category0__c;
    		cate1 = cp.Product__r.Category1__c;
    		cate2 = cp.Product__r.Category2__c;

    		price = cp.Price__c;

    		qNum = cp.Quote__r.Name;
    		mNum = cp.Measure_Calculate__r.Name;
    		adNum = cp.JustPriceProduct__r.AdjustPrice__r.Name;

    		priceListId = cp.Id;
    	}

    	public List<Map<String,Object>> genTableJson(){
    		List<Map<String,Object>> li = new List<Map<String,Object>>();    	
	    	li.add(gMap(this.productName));
	    	li.add(gMap(this.brand ));
	    	li.add(gMap(this.serialNo));
	    	li.add(gMap(this.spec));
	    	li.add(gMap(this.model));
	    	li.add(gMap(this.nccode));
	    	li.add(gMap(this.cate0));
	    	li.add(gMap(this.cate1));
	    	li.add(gMap(this.price));
	    	return li;

    	}

    	public Map<String,Object> gMap (Object obj ){
    		Map<String,Object> pMap = new Map<String,Object>();
	    	pMap.put('title', obj);
	    	return pMap;
    	}

    }






}